<template>
  <view>
    <u-navbar :is-back="true" title="我的申论" :border="false"></u-navbar>
    <u-tabs :list="list" :is-scroll="false" :current="current" @change="change"></u-tabs>
    <u-cell-group>
      <u-cell-item
        v-for="(item, index) in filteredReports"
        :key="index"
        :title="item.title"
        :label="item.time"
        :arrow="true"
        :title-style="{'font-size':'35rpx'}"
        @click="jump(item)"
      >
        <!-- 如果 status 是 1，则显示小红点徽标 -->
        <u-badge v-if="item.status === '1'" is-dot type="error"></u-badge>
      </u-cell-item>
    </u-cell-group>
  </view>
</template>

<script>
import { getUserProfile } from '@/api/system/user';
import { allCorrects, updateCorrect } from '@/api/business/correct'; // 确保引入 updateCorrect
import { getSlpaper } from '@/api/business/slpaper';
import { getSlquestion } from '@/api/business/slquestion';
import { EventBus } from '@/eventBus'; // 引入事件总线

export default {
  data() {
    return {
      list: [{ name: '已批改' }, { name: '未批改' }],
      current: 0,
      reports: [],
    };
  },
  computed: {
    filteredReports() {
          return this.reports.filter(report => {
            if (this.current === 0) {
              // 已批改，显示 status 为 1 和 2 的报告
              return report.status === '1' || report.status === '2';
            } else {
              // 未批改，显示 status 为 0 的报告
              return report.status === '0';
            }
          });
        },
  },
  methods: {
    change(index) {
      this.current = index;
    },
    async jump(item) {
      // 如果状态为 1，更新为 2
      if (item.status === '1') {
        item.status = '2'; // 更新本地状态
        await this.updateStatus(item); // 更新后端状态
      }

      const slreport = encodeURIComponent(JSON.stringify(item));
      console.log('跳转到报告页面，传输的数据:', item);
      uni.navigateTo({
        url: `/subPackageA/report?dttype=2&slreport=${slreport}`,
      });
    },
    async updateStatus(item) {
        try {
          // 发起请求更新状态
          await updateCorrect({
            id: item.id, // 根据你的 API 定义传递相应的字段
            status: '2' // 更新为已读
          });
          // 触发状态更新事件
          EventBus.$emit('statusUpdated'); // 触发事件以更新徽章状态
        } catch (error) {
          console.error('Error updating status:', error);
        }
		},
    async fetchReports() {
      try {
        const userProfile = await getUserProfile();
        const userId = userProfile.userId;
        const response = await allCorrects({ user_id: userId });
        const correctRecords = Array.isArray(response.data) ? response.data : [];
        const reportPromises = correctRecords.map(async record => {
          let title;
          if (record.paper_id) {
            const paperResponse = await getSlpaper(record.paper_id);
            if (paperResponse && paperResponse.data) {
              title = paperResponse.data.name;
            } else {
              title = '未知试卷';
            }
          } else if (record.question_id) {
            const questionResponse = await getSlquestion(record.question_id);
            const question = questionResponse.data;
            if (question && question.type !== undefined) {
              title = this.getQuestionType(question.type);
            } else {
              title = '未知类型';
            }
          }
          return {
            title,
            time: record.dttime,
            status: record.status,
            paper_id: record.paper_id,
            question_id: record.question_id,
            user_answers: record.user_answers,
            grade: record.grade,
            teacher_answers: record.teacher_answers,
            suggested_answers: record.suggested_answers,
            id: record.id // 确保返回 ID 以便更新
          };
        });

        this.reports = await Promise.all(reportPromises); // 等待所有请求完成
      } catch (error) {
        console.error('Error fetching reports:', error);
      }
    },
    getQuestionType(type) {
      const typeMap = {
        '1': '归纳概括',
        '2': '问题对策',
        '3': '分析理解',
        '4': '公文写作',
        '5': '大作文小作文',
      };
      return typeMap[type] || '未知类型';
    },
  },
  mounted() {
    this.fetchReports(); // 组件挂载后获取报告
  },
};
</script>

<style>
.content {
  position: fixed;
  width: 100%;
  height: 100%;
  z-index: -1;
  background-color: #FFFFFF; /* 白色 */
  padding: 10rpx 24rpx;
}

.container {
  padding: 20rpx 0;
  border-bottom: 1px solid #F7F7F7;
}

.name {
  font-size: 32rpx;
}

.message {
  font-size: 24rpx;
  color: #9A9A9A;
}
</style>
